﻿<script setup lang="ts" name="EditImage">
import { FileApi } from '@/api/infra/file'
import { dataURLtoBlob } from '@/utils/file/helper'
import EditImageCropper from './EditImageCropper.vue'
const emit = defineEmits(['save'])
const { error, success } = useMessage()

const EditImageCropperRef: any = ref(null)

const initInfo: any = ref({
  dialogVisible: false,
  info: null,
  form: null,
  imageBase64: null,
  isInit: true
})

// 显示弹窗
const showDialog = (v) => {
  initInfo.value.dialogVisible = true
  FileApi.detail(v.id).then((res: any) => {
    if (res.code === 200) {
      res.data.imagewidth = parseInt(res.data.imagewidth)
      res.data.imageheight = parseInt(res.data.imageheight)
      initInfo.value.info = res.data
      nextTick(() => {
        EditImageCropperRef.value.getInitInfo(res.data)
      })
    }
  })
}

// 子组件将方法暴露给父组件
defineExpose({ showDialog })

// 关闭弹窗
const closeDialog = () => {
  EditImageCropperRef.value.resetInitInfo()
  initInfo.value.dialogVisible = false
}

// 保存
const handleOk = () => {
  const file = dataURLtoBlob(initInfo.value.imageBase64)
  if (initInfo.value.form.title === '') {
    error('图片名称不能为空')
    return false
  }
  const resBody = new FormData()
  if (!initInfo.value.isInit) {
    resBody.append('file', file)
    resBody.append('imagewidth', initInfo.value.form.imagewidth)
    resBody.append('imageheight', initInfo.value.form.imageheight)
  } else {
    resBody.append('file', '')
  }
  resBody.append('title', initInfo.value.form.title)
  resBody.append('id', initInfo.value.info.id)
  resBody.append('alt', initInfo.value.form.alt)
  resBody.append('description', initInfo.value.form.description)
  FileApi.update(resBody).then((res:any) => {
    if (res.code === 200) {
      success('图片编辑成功！')
      emit('save')
      closeDialog()
    }
  })
}

// 图片裁剪
const handleCropper = (obj) => {
  initInfo.value.imageBase64 = obj.value
  initInfo.value.isInit = obj.isInit
  initInfo.value.form = obj.form
}
</script>

<template>
  <ElDialog v-model="initInfo.dialogVisible" title="图片编辑" width="1100px" align-center @close="closeDialog">
    <div class="cropper-panel">
      <EditImageCropper ref="EditImageCropperRef" :circled="false" @fileChange="handleCropper" />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="closeDialog">取消</ElButton>
        <ElButton type="primary" @click="handleOk">确定</ElButton>
      </span>
    </template>
  </ElDialog>
</template>

<style scoped lang="scss"></style>
